﻿using Autofac;
using Loong.Auditing;
using Loong.BackgroundJobs;
using Loong.Dependency;
using Loong.Extensions;
using Loong.Modules;
using Loong.Runtime.Session;
using Loong.Threading;
using Loong.Threading.BackgroundWorkers;
using Loong.Threading.Locks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
using System.Linq.Expressions;

namespace Loong
{
    public sealed class KernelModule : Module, ILoongModule
    {
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            services.AddMemoryCache();
            services.Configure<AuditingOptions>(options =>
            {
                options.IsEnabled = true;
                options.IsEnabledForAnonymousUsers = true;
                options.IgnoredTypes.AddIfNotContains(typeof(Stream));
                options.IgnoredTypes.AddIfNotContains(typeof(Expression));
            });
        }

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterAssemblyByConvention(ThisAssembly);
            builder.RegisterType<ClaimsSession>().As<ILoongSession>().SingleInstance();
            builder.RegisterInstance(SequentialGuidGenerator.Instance).As<IGuidGenerator>().SingleInstance();
        }

        public void Initialize()
        {
            var workerManager = IocManager.IocContainer.Resolve<IBackgroundWorkerManager>();
            workerManager.Add(IocManager.IocContainer.Resolve<IBackgroundJobWorker>());
            workerManager.Start();
        }

        public void Shutdown()
        {
            IocManager.IocContainer.Resolve<IBackgroundWorkerManager>().StopAndWaitToStop();
            IocManager.IocContainer.Resolve<ILockFactory>().Dispose();
        }
    }
}
